// 因素
import axios from '../../resource'

const state = {
  search: {
    questionId: '',
    factorName: '',
    pageNum: '',
    pageSize: 20
  },
  factorList: []
}


const mutations = {
  setFactorList (state, params) {
    state.factorList = params;
  },
  // modify state
  modifyAttr (state, params) {
    copy(state, params);
    function copy (state, params) {
      for (let item in params) {
        let type = Object.prototype.toString.call(params[item]);
        switch (type) {
          case "[object Number]":
          case "[object String]":
          case "[object Boolean]":
            state[item] = params[item]
            break;
          case "[object Array]":
            if (params[item].length) {
              let idx = params[item][0];
              Object.assign(state[item][idx], params[item][1])
            } else {
              state[item] = params[item]
            }
            break;
          default:
            copy(state[item], params[item])
        }
      }
    }
  }
}


const actions = {
  // 因素列表
  index ({state, commit, dispatch}) {
    commit('setLoading', true, { root: true });
    axios({
      url: '/api/factors',
      data: state.search
    }).then(response => {
      commit('setLoading', false, { root: true });
      commit('setFactorList', response)
    })
  },

  // 因素修改
  update ({state, commit, dispatch}, factorId, params) {
    axios({
      url: `/api/factors/${factorId}`,
      data: params,
      method: 'POST'
    }).then(response => {
      dispatch('index')
    })
  },

  // 因素删除
  delete ({state, commit, dispatch}, factorId) {
    axios({
      url: `/api/factors/`,
      data: {'factorId': factorId},
    }).then(response => {
      dispatch('index')
    })
  },

  // 因素添加
  create ({state, commit, dispatch}, params) {
    axios({
      url: `/api/factors/`,
      data: params,
      method: 'POST'
    }).then(response => {
      dispatch('index')
    })
  }
}


export default {
  namespaced: true,
  state,
  actions,
  mutations
}
